package ua.kharkov.knure.dereza.summarytask4.command;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.kharkov.knure.dereza.summarytask4.core.Constants;
import ua.kharkov.knure.dereza.summarytask4.core.EmailSender;
import ua.kharkov.knure.dereza.summarytask4.core.VelocityParser;

/**
 * 
 * Contact to admin command. Sends message via email for admin and client.
 * 
 * @author dereza
 * 
 */
public class ContactToAdminCommand extends Command {

	private static final long serialVersionUID = -5199502031968233849L;

	private static final Logger log = Logger
			.getLogger(ContactToAdminCommand.class);

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse res) {
		log.debug("Command started");

		// gets attribute from request
		String name = (String) req.getParameter("name");
		String surname = (String) req.getParameter("surname");
		String email = (String) req.getParameter("email");
		String question = (String) req.getParameter("question");

		// creates hashmap which will be used for creating emails
		HashMap<String, String> parameters = new HashMap<String, String>();
		parameters.put("name", name);
		parameters.put("surname", surname);
		parameters.put("email", email);
		parameters.put("question", question);
		log.trace("Data for template --> " + parameters);

		// error handler
		String errorMessage = null;
		try {
			// creates messages for client and admin
			VelocityParser velocity = new VelocityParser();
			String emailForAdmin = velocity.getMessage(
					Constants.VELOCITY_FILE_TEMPLATE_FOR_ADMIN, parameters);
			String emailForClient = velocity.getMessage(
					Constants.VELOCITY_FILE_TEMPLATE_FOR_CLIENT, parameters);

			// sends messages
			EmailSender sender = new EmailSender();
			sender.sendMessage(Constants.MAIL_ADMIN, emailForAdmin);
			sender.sendMessage(email, emailForClient);
		} catch (Error ex) {
			errorMessage = "Internal error. Cannot send email.";
			log.error("errorMessage --> " + errorMessage);
		}
		log.debug("Command finished");
		return null;
	}

	@Override
	public String toString() {
		return "ContactToAdmin";
	}
}